import { each } from "lodash";
import React, { useState, useEffect, useMemo } from "react";
import { RendererPropTypes } from "@/visualizations/prop-types";
import getChartData, { getParameter, getScheme } from "../getChartData";
import { prepareCustomChartData, createCustomThreeRenderer } from "../plotly";
import $ from "jquery";

export default function CustomThree({ options, data, row, onClickHandler, onRefreshDashboardHandler, onRefreshWidgetHandler, onExpandDashboardHandler }) {
  const [container, setContainer] = useState(null);
  const [customCode, setCustomCode] = useState(options.customCode);

  const renderCustomThree = useMemo(() => createCustomThreeRenderer(customCode, options.enableConsoleLogs), [
    customCode,
    options.enableConsoleLogs,
  ]);

  const plotlyData = useMemo(() => prepareCustomChartData(getChartData(data.rows, options)), [options, data]);
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_mode');
 
  function doRender() {
    const scheme = getScheme(showPortal);
    const parameter = getParameter();

    require.ensure([], function(require) {
      import(/* webpackChunkName:"three" */ 'three').then((THREE) => {
        if (!window.THREE) window.THREE = THREE;
        if (!window.$) window.$ = $;

        try {
          renderCustomThree(data && data.rows, plotlyData.x, plotlyData.ys, container, scheme, parameter, THREE, $,
            row || (data && data.rows && data.rows.length>0 && data.rows[0]), 
            options.clickEnabled ? onClickHandler : ()=>{}, 
            onRefreshDashboardHandler, onRefreshWidgetHandler, onExpandDashboardHandler);
        } catch (err) {
          if (options.enableConsoleLogs) console.log(`自定义3D视图错误: ${err}`); // eslint-disable-line no-console
        }  
      });
    }, 'three');
  }

  const cssstyle = showPortal ? {
    width: '100%',
    height: '100%',
    background: "#00000000",
    color: localStorage.getItem('colorstyle_color'),
  } : {
    width: '100%',
    height: '100%',
  }

  useEffect(() => {
    if (container) doRender();
    return componentWillUnmount;
  }, [container]);

  function componentWillUnmount() {
    if (container) container.innerHTML = '';
  }

  return  <div ref={setContainer} style={cssstyle} />;
}

CustomThree.propTypes = RendererPropTypes;
